package com.itlaobing.exam.service;

import com.itlaobing.exam.dao.UserDao;
import com.itlaobing.exam.entity.User;
import com.itlaobing.foundation.support.EncryptHelper;
import com.itlaobing.foundation.support.EncryptType;
import com.itlaobing.foundation.support.StringHelper;

import java.time.LocalDate;
import java.util.logging.Logger;

public class UserService {

    private final Logger logger = Logger.getLogger( this.getClass().getName() );

    private UserDao userDao = new UserDao();

    public boolean saveUser( User user ) {

        Integer id = userDao.nextId(); // 获得 t_users 表中下一个主键
        user.setId( id ); // 将查询到的 id 设置到 user 对象中

        final String salt = StringHelper.random( 10 );
        user.setSalt( salt ); // 为user对象设置盐值

        final String password = user.getPassword() ; // 获得用户指定的原始密码

        String encrypted = this.encrypt(password, salt); // 调用加密方法对原始密码加盐加密

        user.setPassword( encrypted ); // 将加盐且加密后的字符串设置到user对象中

        user.setJoin_date( LocalDate.now() ); // 设置 加入日期

        return userDao.save( user );
    }

    /**
     * 对原始密码加盐、加密
     * @param password 原始密码
     * @param salt 盐值
     * @return 返回加密后的字符串
     */
    public String encrypt( final String password , final String salt ) {
        String passwordWithSalt = salt.substring( 0 , 5 ) + password + salt.substring( 5 );
        String encrypted = EncryptHelper.encrypt( passwordWithSalt , EncryptType.SHA1 );
        return encrypted;
    }

    public User findUser( String username ) {
        logger.info( "根据用户名获取用户" );
        return userDao.find( username );
    }

    public boolean editUser( User user ) {
        logger.info( "修改用户个人信息" );
        return userDao.edit( user );
    }

    public boolean changeUser( User user ) {
        logger.info( "修改用户个人密码" );

        final String salt = user.getSalt(); // 获取用户指定的原始盐值
        final String password = user.getPassword() ; // 获得用户指定的原始密码
        String encrypted = this.encrypt(password, salt); // 调用加密方法对原始密码加盐加密
        user.setPassword( encrypted ); // 将加盐且加密后的字符串设置到user对象中
        return userDao.change( user );
    }

    public boolean deleteUser( User user ) {
        logger.info( "删除用户" );
        return userDao.delete( user );
    }

}
